import { defineStore } from 'pinia'

export const useProductStore = defineStore('product', {
  // 状态
  state: () => ({
    // 商品列表
    products: [],
    // 商品分类
    categories: [],
    // 当前选中的分类
    currentCategory: null,
    // 搜索关键词
    searchKeyword: '',
    // 排序方式
    sortBy: 'default',
    // 筛选条件
    filters: {
      priceRange: null,
      brands: [],
      tags: []
    },
    // 加载状态
    loading: false,
    // 商品详情缓存
    productDetails: new Map()
  }),

  // 计算属性
  getters: {
    // 获取筛选后的商品列表
    filteredProducts: (state) => {
      let result = [...state.products]
      
      // 分类筛选
      if (state.currentCategory) {
        result = result.filter(p => p.categoryId === state.currentCategory)
      }
      
      // 关键词搜索
      if (state.searchKeyword) {
        const keyword = state.searchKeyword.toLowerCase()
        result = result.filter(p => 
          p.name.toLowerCase().includes(keyword) ||
          p.description.toLowerCase().includes(keyword)
        )
      }
      
      // 价格区间筛选
      if (state.filters.priceRange) {
        const [min, max] = state.filters.priceRange
        result = result.filter(p => p.price >= min && p.price <= max)
      }
      
      // 品牌筛选
      if (state.filters.brands.length) {
        result = result.filter(p => state.filters.brands.includes(p.brand))
      }
      
      // 标签筛选
      if (state.filters.tags.length) {
        result = result.filter(p => 
          p.tags.some(tag => state.filters.tags.includes(tag))
        )
      }
      
      // 排序
      switch (state.sortBy) {
        case 'price-asc':
          result.sort((a, b) => a.price - b.price)
          break
        case 'price-desc':
          result.sort((a, b) => b.price - a.price)
          break
        case 'sales':
          result.sort((a, b) => b.sales - a.sales)
          break
        case 'rating':
          result.sort((a, b) => b.rating - a.rating)
          break
      }
      
      return result
    },
    
    // 获取热门商品
    hotProducts: (state) => {
      return state.products
        .filter(p => p.sales > 100)
        .sort((a, b) => b.sales - a.sales)
        .slice(0, 10)
    },
    
    // 获取推荐商品
    recommendProducts: (state) => {
      return state.products
        .filter(p => p.rating >= 4.5)
        .sort((a, b) => b.rating - a.rating)
        .slice(0, 10)
    }
  },

  // 操作方法
  actions: {
    // 获取商品列表
    async fetchProducts() {
      this.loading = true
      try {
        // TODO: 调用获取商品列表API
        const data = await fetchProductsApi()
        this.products = data
      } catch (error) {
        console.error('获取商品列表失败：', error)
      } finally {
        this.loading = false
      }
    },

    // 获取商品分类
    async fetchCategories() {
      try {
        // TODO: 调用获取分类API
        const data = await fetchCategoriesApi()
        this.categories = data
      } catch (error) {
        console.error('获取商品分类失败：', error)
      }
    },

    // 获取商品详情
    async fetchProductDetail(productId) {
      // 检查缓存
      if (this.productDetails.has(productId)) {
        return this.productDetails.get(productId)
      }

      try {
        // TODO: 调用获取商品详情API
        const data = await fetchProductDetailApi(productId)
        // 存入缓存
        this.productDetails.set(productId, data)
        return data
      } catch (error) {
        console.error('获取商品详情失败：', error)
        return null
      }
    },

    // 设置当前分类
    setCategory(categoryId) {
      this.currentCategory = categoryId
    },

    // 设置搜索关键词
    setSearchKeyword(keyword) {
      this.searchKeyword = keyword
    },

    // 设置排序方式
    setSortBy(sortBy) {
      this.sortBy = sortBy
    },

    // 设置筛选条件
    setFilters(filters) {
      this.filters = { ...this.filters, ...filters }
    },

    // 清除筛选条件
    clearFilters() {
      this.filters = {
        priceRange: null,
        brands: [],
        tags: []
      }
      this.currentCategory = null
      this.searchKeyword = ''
      this.sortBy = 'default'
    }
  },

  // 持久化配置
  persist: {
    enabled: true,
    strategies: [
      {
        key: 'product',
        storage: sessionStorage,
        paths: ['currentCategory', 'filters', 'sortBy'] // 只持久化用户选择的条件
      }
    ]
  }
})